

var TimeFilterItem = React.createClass({
    render: function() {
        var className=this.props.selected?"bg-success selected":"bg-primary";
        return (<th className={className} onClick={this.props.onClick}><a href="javascript:;"><div>{this.dateString()}</div><div>{this.props.item.label}</div></a></th>);
    },
    dateString:function(){
        return new Date(this.props.item.from).Format("MM-dd");
    }
});


var ProductRow = React.createClass({
    handleOpenDetail:function(productId,url){
      toPage('ProductDetailPage',{customerId:customerId,id:productId});
      return false;
    },
    getInitialState: function() {
        return {status: ''};
    },
    componentDidMount: function() {

    },
    render: function() {
        var product = this.props.product;
        var cssClass = "panel panel-info col-xs-12 col-md-6 grid-item";
        var status = <b className="mustsee">报名结束</b>;
        if(product.dueTime&&product.dueTime>new Date()){
            status = <b className="mustsee open">报名中</b>;
            cssClass = "panel panel-info col-xs-12 col-md-6 grid-item open";
        }

        var startTime=new Date(product.startTime).Format('MM-dd hh:mm')+' - '+new Date(product.endTime).Format('hh:mm');
        var dueTime=new Date(product.dueTime).Format('MM-dd hh:mm')
        var picture=product.picture?'/api/thumb/'+product.picture+'/64/64':"http://img12.360buyimg.com/n5/jfs/t568/247/767541758/113299/4c1bc48b/5486c773Nac5da862.jpg";
        var location=product.location||{}
        var attributes=product.attributes||{}
        var distance=getGPSDistance(mylocation.lat,mylocation.lng,location.lat,location.lng)+' km'
        return (
        <div className={cssClass}>
        <a onClick={this.handleOpenDetail.bind(this,product.id,"/activities/detail.html?id="+product.id)} href="#">
          <div className="panel-heading">{product.partnerName}<span className="pull-right">{distance}</span></div>
          <div className="panel-body">
                <table width="100%">
                    <tbody>
                        <tr>
                            <td width="100"><div><img width="64" src={picture}/></div></td>
                            <td colSpan="3">
                                <div><div><a  ><b>[{product.cat1}]{product.name}</b></a></div></div>
                                <div><span className="glyphicon glyphicon-map-marker" aria-hidden="true"/>{product.shopName}</div>
                            </td>
                        </tr>
                        <tr>
                            <td><div><span className="glyphicon glyphicon-user"/>{product.quantity-product.stock}/{product.quantity}人</div></td>
                            <td colSpan="2"><div><span className="glyphicon glyphicon-time"/>{startTime}</div></td>
                            <td><div><span className="glyphicon glyphicon-yen"/>{product.price}/人</div></td>
                        </tr>
                        <tr>
                            <td><div>{status}</div></td>
                            <td colSpan="3">
                                <div><strong>♂{attributes.male||0} / ♀{attributes.female||0} </strong><small>报名截止时间：{dueTime} </small></div>
                            </td>
                        </tr>
                    </tbody>
                </table>
          </div>
          </a>
        </div>

        );
    }
});

var ProductList = React.createClass({
    loadedUrl:'',
    getInitialState: function() {
        return {products: []};
    },
    componentDidMount: function() {

    },
    render: function() {
        //console.log(this.props.url);
        var self=this;
        var url=self.props.url;
        if(url&&self.loadedUrl!=url){
            $.get(url,function(data){
                //console.log(data.content);
                self.loadedUrl=url;
                self.setState({products: data.content});
            })
        }
        var rows = [];
        var lastCategory = null;
        this.state.products.map(function(product) {
            rows.push(<ProductRow product={product} key={product.name} />);
            lastCategory = product.category;
        });
        return (

                <div className="ProductList row grid">{rows}</div>
        );
    }
});

var FilterableProductTable = React.createClass({
    initFilterItems:function(selectedItem){
        var nowTimeStamp=new Date().getTime();
        nowTimeStamp=nowTimeStamp-nowTimeStamp%(24*3600000)-8*3600000;
        var items= [
                                                   {label:"今天",selected:false,from:nowTimeStamp,to:nowTimeStamp+3600000*24},
                                                   {label:"明天",selected:false,from:nowTimeStamp+3600000*24,to:nowTimeStamp+3600000*24*2},
                                                   {label:"后天",selected:false,from:nowTimeStamp+3600000*24*2,to:nowTimeStamp+3600000*24*3},
                                                   {label:"两天后",selected:false,from:nowTimeStamp+3600000*24*3}
                                               ];
        if(selectedItem)
            items[selectedItem-1].selected=true;
        return items;
    },
    getInitialState: function() {
        var items=this.initFilterItems(1);
        return {url:null,items:items,item:items[0]};
    },
    handleClick: function(item,i) {
        //console.log('You clicked: ' + item);
        var fromThatDay=item.to?"":"&from=true"
        API.wxLocation(function(point){
            if(point){
                mylocation=point;
                //this.setState({url:"/api/products/near/location?lat="+point.lat+"&lng="+point.lng+"&date="+item.from+fromThatDay});
            }
        }.bind(this))
        point=mylocation;
        var items=this.initFilterItems(i+1)
        this.setState({url:"/api/products/near/location?lat="+point.lat+"&lng="+point.lng+"&date="+item.from+fromThatDay,items:items,item:items[i]});
    },
    handleCityChanged:function(data){
        var item=this.state.item||{};
        var fromThatDay=item.to?"":"&from=true";
        if(data.city){
            this.setState({url:'/api/products?city='+data.city+'&date='+item.from+fromThatDay})
        }else{
            point=mylocation;
            this.setState({url:"/api/products/near/location?lat="+point.lat+"&lng="+point.lng+"&date="+item.from+fromThatDay});
        }
    },
    componentDidMount: function() {
        //wx.ready(function(){
            API.wxLocation(function(point){
                if(point){
                    mylocation=point;
                }
            })
            point=mylocation;
            this.setState({url:"/api/products/near/location?lat="+point.lat+"&lng="+point.lng+"&date="+new Date().getTime()});
        //})
        
    },
    render: function() {
        var items=[];
        var self=this;
        this.state.items.map(function(item,i){
            items.push(<TimeFilterItem item={item} selected={item.selected} onClick={self.handleClick.bind(self,item,i)} />);
        });
        return (

            <div className="clear-both">
                <ProductQueryBar onChange={this.handleCityChanged}/>
                <ProductList url={this.state.url} />
                <nav className="navbar navbar-default navbar-fixed-bottom">
                  <div >
                    <table width="100%" className="TimeFilterTable">
                       <thead><tr>{items}</tr></thead>
                    </table>
                  </div>
                </nav>
            </div>
        );
    }
});

var HomePage = FilterableProductTable

var ProductQueryBar = React.createClass({
    handleToggle:function(){
        var node=this.getDOMNode();
        if($(node).hasClass("toggle")){
            $(node).removeClass("toggle");
            this.state.city=null;
            this.setState(this.state)
            this.fireUpdate();
        }else{
            $(node).addClass("toggle");
        }
    },
    handleCityChanged:function(e,x){
        this.state.city=$(e.target).val()
        this.setState(this.state)
        this.fireUpdate();
    },
    getInitialState: function() {
        return {
            city: null
        };
    },
    fireUpdate:function(){
        if(this.props.onChange){
            this.props.onChange(this.state);
        }
        console.log(this.state)
    },
    render:function(){
        return (<div className="querybar">
            <CitySelector inline="true" onChange={this.handleCityChanged} />
            <button className="btn btn-default" onClick={this.handleToggle}><span className="glyphicon glyphicon-backward"/></button>
            </div>)
    }
})

var ProductDetailPage = React.createClass({
    handlePartyModal:function(){
        $('#partyModal',this.getDOMNode()).modal('show');
    },
    handleClickPartner: function(){
        //alert(this.state.product.partner);
    },
    getInitialState: function() {
        return {product:{name:''},canBuy:false}
    },
    componentDidMount: function() {
        //console.log('componentDidMount');
        var self=this;
        API.getProduct({productId:this.props.id},function(data){
            document.title=data.name
            self.setState({product:data});
        })
        if(this.props.customerId){
            $.get('/api/customers/'+this.props.customerId+'/orders/single/step',{product_id:this.props.id,amount:1},function(data){
                self.setState({canBuy:true});
            })
        }
    },
    render: function() {
        var product=this.state.product;
        var partner=product.partner||{};
        var location=product.location||{};
        var attributes=product.attributes||{};
        var cr=product.creator||{};
        var jModal=null;
        var btn=null;
        if(this.props.customerId){
            if(this.state.canBuy&&product.dueTime&&product.dueTime>new Date()){
                btn= <a href="javascript:;" onClick={this.handlePartyModal} className="btn btn-success col-md-4 col-xs-12">我要报名</a>;
                jModal=<JoinPartyModal product={product} id={product.id} customerId={this.props.customerId} />
            }else{
                //btn=<a href="javascript:;" className="btn btn-warning col-md-4 col-xs-12">报名结束</a>;
            }
        }
        var startTime=new Date(product.startTime).Format('MM-dd hh:mm')+' - '+new Date(product.endTime).Format('hh:mm');
        return (
        <div className="ProductDetailPage clear-both">
            <div ><h3>{product.name}<small>{startTime}</small></h3></div>
            <div className="row center-block">{btn}</div>
            <table width="100%" className="table table-striped table-condensed">
                <tr><td width="60"><label>组织者</label></td><td>{attributes.creator} - <a href={"tel:"+attributes.phone}> {attributes.phone} </a></td><td width="20"></td></tr>
                <tr><td width="60"><label>活动地点</label></td><td><a className="b" href={"http://m.amap.com/navi/?dest="+location.lng+","+location.lat+"&destName="+product.shopName+"&hideRouteIcon=1&key="+amapKey}><span className="glyphicon glyphicon-map-marker" aria-hidden="true"></span>{product.shopName}</a></td><td width="20"><span className="glyphicon glyphicon-menu-right" aria-hidden="true"></span></td></tr>
            
                <tr onClick={this.handleClickPartner}><td width="60"><label>俱乐部</label></td><td><a className="b"  onClick={function(){toPage('PartnerDetailPage',{customerId:customerId,id:partner.id})}} href="javascript:;">{partner.name}</a></td><td width="20"><span className="glyphicon glyphicon-menu-right"/></td></tr>
                <tr><td width="60"><label>活动时段</label></td><td>{startTime}</td><td width="20"></td></tr>
                <tr><td width="60"><label>人均费用</label></td><td>{product.price}/人</td><td width="20"></td></tr>
                <tr><td width="60"><label>报名情况</label></td><td>{product.quantity-product.stock}/{product.quantity}人</td><td width="20"></td></tr>
                <tr><td width="60"><label>男女比</label></td><td>♂{attributes.male||0} / ♀{attributes.female||0}</td><td width="20"></td></tr>
                <tr><td width="60"><label>备注</label></td><td>{product.remark}</td><td width="20"></td></tr>
            </table>

            <div className="row center-block"><a onClick={API.wxShare} className="btn btn-primary col-xs-12" href="javascript:;">分享</a></div>
            {jModal}
        </div>
            );
    }
});

